package com.sz.app.edi.aspect;

import com.sz.app.edi.base.entity.SynCompanyAccount;
import com.sz.app.edi.constants.EdiErrorCodes;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;


@Component
class CommonAuth {

    private static final String EDI_GET_TOKEN = "/edi/api/v1/token";

    private static final String FUNCODE_IP_SPLIT = ",";

    /**
     * 是否生成token请求
     *
     * @param method 访问url
     * @return boolean
     */

    static boolean isGenerateToken(String method) {
        return (!StringUtils.isEmpty(method) && EDI_GET_TOKEN.equals(method));
    }

    /**
     * 验证用户访问接口的权限
     *
     * @param synCompanyAccount synCompanyAccount
     * @param funcCode          funcCode
     */

    static void validFunctionPermission(SynCompanyAccount synCompanyAccount, String funcCode) {
        String permissions = synCompanyAccount.getPermission();
        if (StringUtils.isEmpty(funcCode)) {
            throw Exceptions.bizException(EdiErrorCodes.ERROR_ARGUMENT_EMPTY, "funCode");
        }
        if (!StringUtils.isEmpty(permissions) && !permissions.contains(funcCode)) {
            //没有访问权限
            throw Exceptions.bizException(EdiErrorCodes.ERROR_EDI_NO_PERMISSION);
        }
    }

    /**
     * 验证用户ip是否存在白名单中
     *
     * @param synCompanyAccount synCompanyAccount
     * @param ip                待验证的ip
     */

    static void validIP(SynCompanyAccount synCompanyAccount, String ip) {
        if (null != synCompanyAccount) {
            //系统访问ip白名单
            String permissionedIp = synCompanyAccount.getPermissionedIp();
            if (!StringUtils.isEmpty(permissionedIp) && !permissionedIp.contains(ip)) {
                //ip没有在白名单里面
                throw Exceptions.bizException(EdiErrorCodes.ERROR_EDI_IP_NOT_ON_WHITE_LIST);

            }
        }
    }


}
